//'use strict';
/*
 var defaultLang='zh-TW';
 var msg = {
 'ERROR_DB_SETUP':
 {'zh-TW':'資料庫建立錯誤'}
 };
 */
var serverURL = 'http://localhost:16870';
var imgProcessPath = '/img.php';
var classInfo = {'甲': ['aa', 'bb', 'cc'], '乙': ['dd', 'ee', 'ff']};
var session_id = null;
//var dbConfig={dbName:'sessionDB',dbVer:'1.0',dbShowName:'sessionData',dbSize:1000000};
var app = angular.module('MobileAngularUiExamples', [
    "ngRoute",
    "ngTouch",
    "mobile-angular-ui"
]);

document.addEventListener("deviceready", onDeviceReady, false);
var db;
var app_dir = 'schoolCamera';
var photo_dir = 'photo';
var sess_file = 'sess';
function createDirectory(entry, path) {
    var dirs = path.split("/").reverse();
    root = entry;
    finalDir = null;

    var createDir = function (dir) {
        root.getDirectory(dir, {
            create: true,
            exclusive: false
        }, successCB, failCB);
    };

    var successCB = function (tmp_entry) {
        finalDir = tmp_entry;
        if (dirs.length > 0) {
            root = tmp_entry;
            createDir(dirs.pop());
        } else {

            console.log("all dir created");
        }
    };

    var failCB = function () {
        console.log("failed to create dir " + dir);
    };

    createDir(dirs.pop());
}
function accessSingleData(dirName, fileName, access_mode, data) {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
        function (fs) {
            fs.root.getDirectory(dirName, {create: true, exclusive: false},
                function (dir) {
                    dir.getFile(fileName, {create: true, exclusive: false},
                        function (fileEntry) {
                            if (access_mode == 'write') {
                                return writeData(fileEntry, data);
                            }
                            else if (access_mode == 'read') {
                                return getData(fileEntry);
                            }
                        }, function () {
                            console.log('session file error');
                        });
                },
                function () {
                    console.log('session directory error occur');
                });
        },
        function () {
            console.log('filesystem read error');
        });
}
function writeData(fileEntry, data) {
    fileEntry.createWriter(function (writer) {
        writer.write(data);
    }, function () {
        console.log('write error');
    });

}
function getData(fileEntry) {
    var reader = new FileReader();
    reader.onloadend = function (evt) {
        console.log("Read as text");
        console.log(evt.target.result);
    };
    reader.readAsText(fileEntry);


}
function onDeviceReady() {
//    var sess=accessSingleData(sess_dir,sess_file,'read');
//    if(sess!='') {
//
//    }
}


/*
 app.service('storageService',function(){

 });
 app.service('sessionService',[dbConfig,function(dbConfig){
 this.get = function(){

 };
 this.set = function() {

 };
 this.remove = function() {

 };
 }]);
 app.service('loginService',['$http',function($http){
 this.checkLogin = function() {
 var $promise=$http.post('dispatcher.php',data);
 $promise.then(function(result){
 var isLogin=result.data;
 if(isLogin) {
 return true;
 }
 else {
 return false;
 }
 });
 };
 this.login = function(username,pwd) {
 //         var $http.post('dispatcher.php',data);
 };
 }]);
 */
app.service('uploadInfoService', function () {
    var photoURIList = [];
    var className;

    return {
        getPhotoList: function () {
            return photoURIList[0];
        },
        pushPhotoList: function (photo) {
            photoURIList.push(photo);
        },
        removePhotoList: function (photo) {
            photoURIList.splice(photoURIList.indexOf(photo), 1)
        },
        setClass: function (className) {
            className = className;
        },
        getClass: function () {
            return className;
        }
    };
});
app.controller('loginController', function () {
});
app.controller('MainController', function ($rootScope, $scope, analytics) {
    $rootScope.$on("$routeChangeStart", function () {
        $rootScope.loading = true;
    });
    $rootScope.$on("$routeChangeSuccess", function () {
        $rootScope.loading = false;
    });
});
function display(element, value) {
    if (typeof element !== 'undefined')
        element.style.display = value;
}
function imgChange(element, value) {
    element.src = value;
}

app.controller('cameraController', ['$scope', function ($scope) {
    $scope.takePhoto = function () {
        navigator.camera.getPicture(function (imgURI) {
            console.log('info:' + imgURI);
            imgChange(document.getElementById('photoPreviewImg'), imgURI);
//            display(document.getElementById('cameraToolbar'),'block');
        }, function () {
            console.log('camera fail');
        }, { quality: 100,
            destinationType: Camera.DestinationType.FILE_URI
        });
    };
    $scope.savePreview = function () {
        var tmp_path = document.getElementById('photoPreviewImg').src;
        window.resolveLocalFileSystemURI(
            tmp_path,
            function (entry) {
                console.log('entryname' + entry.name);
                window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
                    rootPath = fileSystem.root;
                    window.resolveLocalFileSystemURI(rootPath.fullPath + '/' + app_dir + '/' + photo_dir, function (dirEntry) {
                        entry.copyTo(dirEntry, new Date().getTime() + '.jpg', null, null);
                        console.log('isDirectory' + dirEntry.isDirectory);
                        console.log('root.fullPath' + dirEntry.fullPath);
                        console.log('directory fullpath:' + dirEntry.fullPath);
                    }, null);
                    //        display(document.getElementById('cameraToolbar'),'none');
                }, null);


            },
            null
        );
        alert('儲存成功');
//        tmp_path = tmp_path.substring(8);
//        console.log('tmp_path'+tmp_path);
//        fe = new FileEntry({fullPath:tmp_path});

        this.takePhoto();
    };
    $scope.takePhoto();
}]);
app.controller('photoGalleryController', ['$scope','uploadInfoService','$location',function ($scope, uploadInfoService,$location) {
    var i;
    $scope.photos = [];
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onRequestFileSystemSuccess, null);
    function onRequestFileSystemSuccess(fileSystem) {
        var entry = fileSystem.root;
        createDirectory(entry, app_dir + '/' + photo_dir);
//        console.log('dir fullpath:'+dirEntry.fullPath);
        entry.getDirectory(app_dir + '/' + photo_dir, {create: true}, function (dirEntry) {
            var directoryReader = dirEntry.createReader();
            directoryReader.readEntries(function (entries) {
                for (i = 0; i < entries.length; i++) {
                    $scope.photos.push(entries[i].fullPath);
                }
            }, function () {
                console.log('dir file retrieve error');
            });
        });
//        entry.getDirectory(app_dir, {create: true, exclusive: false}, onGetDirectorySuccess, onGetDirectoryFail);
    }

    function onGetDirectoryFail(error) {
        console.log("Error creating directory " + error.code);
    }

    function onGetDirectorySuccess(dir) {
        console.log('dir name:' + dir.name);
        console.log(app_dir + '/' + photo_dir);
        var directoryReader = dirEntry.createReader();
        directoryReader.readEntries(function () {
            console.log('length:' + entries.length);
            for (i = 0; i < entries.length; i++) {
                $scope.photos.push(entries[i].name);
                console.log(entries[i].name);
            }
        }, function () {
            console.log('dir file retrieve error');
        });
    }

    $scope.photoPick = function (photo) {
        alert('test');
        alert(photo);
        uploadInfoService.pushPhotoList(photo);
        $location.path('/classList');
//        if (uploadInfoService.getPhotoList().indexOf(photo) === -1) {
//            uploadInfoService.pushPhotoList(photo);
//        }
//        else {
//            uploadInfoService.removePhotoList(photo);
//        }
    };

//    dirEntry = new DirectoryEntry({fullPath: app_dir+'/'+photo_dir});

}]);
app.controller('nameListController', ['$scope','uploadInfoService', function ($scope, uploadInfoService) {
    var namePickedList = [];
    alert(uploadInfoService.getClass());
    $scope.nameList = classInfo[uploadInfoService.getClass()];
    console.log(nameList);
    $scope.namePick = function (name) {
        var tmp_index = namePickedList.indexOf(name);
        if (tmp_index === -1) {
            namePickedList.push(name);
        }
        else {
            namePickedList.splice(tmp_index, 1);
        }
    };
    $scope.upload = function () {
        var ft = new FileTransfer();
        var options = new FileUploadOptions();
        options.fileKey = "img";
        options.fileName = imagefile.substr(imagefile.lastIndexOf('/') + 1);
        options.mimeType = "image/jpeg";
        var params = new Object();
        params.nameList = namePickedList;
        options.params = params;
        options.chunkedMode = false;
        ft.upload(uploadInfoService.getPhotoList(), serverURL + imgProcessPath, null, null, options);
    };
    alert(nameList.length);
    $scopre.go = function (path) {
        alert('test');
        $location.path(path);
    };
}]);
app.controller('classListController', ['$scope','uploadInfoService','$location',function ($scope, uploadInfoService,$location) {
    $scope.classList = [];
    for(var className in classInfo) {
        $scope.classList.push(className);
    }
    $scope.pickClass = function(className) {
        alert(className);
        uploadInfoService.setClass(className);
        $location.path('/nameList');
    }
}]);
app.service('analytics', [
    '$rootScope', '$window', '$location', function ($rootScope, $window, $location) {
        var send = function (evt, data) {
            ga('send', evt, data);
        }
    }
]);

app.config(function ($routeProvider) {
    $routeProvider
        .when('/login', {templateUrl: "template/login.html", controller: 'loginController'})
        .when('/main', {templateUrl: "template/main.html", controller: 'mainController'})
        .when('/logout', {templateUrl: "template/logout.html", controller: 'logoutController'})
        .when('/camera', {templateUrl: "template/camera.html", controller: 'cameraController'})
        .when('/photoGallery', {templateUrl: "template/photoGallery.html", controller: 'photoGalleryController'})
        .when('/setting', {templateUrl: "template/setting.html", controller: 'settingController'})
        .when('/nameList', {templateUrl: "template/nameList.html", controller: 'nameListController'})
        .when('/classList', {templateUrl: "template/classList.html", controller: 'classListController'})
        .otherwise({redirectTo: '/login'});
});
